﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SenGe.Domain;
using System.Security.Claims;

namespace SenGe.Web
{
    /// <summary>
    /// 自定义Action过滤器
    /// </summary>
    public class MyActionFilter : IActionFilter
    {
        /// <summary>
        /// 在action执行完毕后，将当前登录用户信息返回给视图
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            // 在Action执行后调用
            if (context.Controller is Controller controller)
            {
                // 获取当前用户
                var user = context.HttpContext.User;

                if (user.Identity?.IsAuthenticated ?? false)
                {
                    // 从Claims中获取用户信息
                    string? id = user.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0";
                    string? name = user.FindFirst(ClaimTypes.Name)?.Value ?? "未知用户";
                    DtoCurrentUser dtoCurrentUser = new DtoCurrentUser()
                    {
                        Id = long.Parse(id),
                        Name = name
                    };
                    if (user.FindFirst("Avatar")?.Value?.Length > 0) dtoCurrentUser.Avatar = user.FindFirst("Avatar")?.Value;
                    // 将用户信息添加到ViewData
                    controller.ViewData["CurrentUser"] = dtoCurrentUser;

                    //返回菜单状态信息
                    if (!controller.ViewData.Keys.Contains("MenuIndex"))
                    {
                        string? controllerName = "Home";
                        string? actionName = "Index";
                        RouteValueDictionary? routeValues = context.RouteData.Values;
                        if (routeValues?.Count > 0)
                        {
                            if (routeValues.Keys.Contains("controller")) controllerName = routeValues["controller"]?.ToString();
                            if (routeValues.Keys.Contains("action")) actionName = routeValues["action"]?.ToString();
                        }
                        controller.ViewData["MenuIndex"] = $"/{controllerName}/{actionName}";
                    }
                }
                else
                {
                    controller.ViewData["CurrentUser"] = null;
                }
            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            // 在Action执行前调用
        }
    }
}
